package com.jiangyg.devtools.toolkit;

import org.apache.commons.lang.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类描述：驼峰命名工具类
 *
 * @author jiangyg
 * @date 2023-08-13
 */
public class CamelCaseUtils {

    public static final char UNDERLINE = '_';

    /**
     * 功能描述：驼峰命名转下划线
     *
     * @param param 驼峰格式字符串
     * @return 下换线格式字符串
     */
    public static String camelToUnderline(String param) {
        if (StringUtils.isEmpty(param)) {
            return StringUtils.EMPTY;
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 功能描述：转驼峰命名
     *
     * @param param 下划线格式字符串
     * @return 驼峰格式字符串
     */
    public static String underlineToCamel(String param) {
        if (StringUtils.isEmpty(param)) {
            return StringUtils.EMPTY;
        }
        String str = param.toLowerCase();
        int len = str.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (c == UNDERLINE) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(str.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 功能描述：正则表达式转驼峰命名
     *
     * @param param 下划线格式字符串
     * @return 驼峰格式字符串
     */
    public static String underlineToCamel2(String param) {
        if (StringUtils.isEmpty(param)) {
            return StringUtils.EMPTY;
        }
        String str = param.toLowerCase();
        StringBuilder sb = new StringBuilder(str);
        Matcher mc = Pattern.compile("_").matcher(str);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }

}
